package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.igas.momp.facade.QueryMemberInfoService;
import cc.rengu.igas.momp.facade.base.Header;
import cc.rengu.igas.momp.facade.bean.MembershipDetailInfoBean;
import cc.rengu.igas.momp.facade.bean.MembershipInfoBean;
import cc.rengu.igas.momp.facade.request.QueryMemberDetailInfoRequest;
import cc.rengu.igas.momp.facade.request.QueryMemberInfoRequest;
import cc.rengu.igas.momp.facade.response.QueryMemberDetailInfoResponse;
import cc.rengu.igas.momp.facade.response.QueryMemberInfoResponse;
import cc.rengu.igas.momp.facade.result.Result;
import cc.rengu.redp.bizimpl.enums.MompTxnNumEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.service.MemberManagerService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service("memberManagerService")
public class MemberManagerServiceImpl implements MemberManagerService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    QueryMemberInfoService queryMemberInfoService;

    private String getOrgCode(String orgCode) {
        if (orgCode.length() >= 14) {
            return orgCode.substring(0, 14);
        }
        int length = orgCode.length();
        StringBuffer sb = null;
        while (length < 14) {
            sb = new StringBuffer();
            sb.append("0").append(orgCode);
            orgCode = sb.toString();
            length = orgCode.length();
        }
        return orgCode;
    }

    /**
     * 查询会员List
     *
     * @param queryParam
     * @param pageable
     * @return
     */
    public IPage<MembershipInfoBean> getMemberList(QueryMemberInfoRequest queryParam, QueryRequest pageable) throws RedpException {
        Result<QueryMemberInfoResponse> result = null;
        try {
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            String orgCode = getOrgCode(user.getOrgCode());
            //设置入参
            queryParam.setQueryId(user.getId());
            queryParam.setQueryOrgId(user.getOrgCode());
            queryParam.setPageIndex(String.valueOf(pageable.getPageNum()));
            queryParam.setPageSize(String.valueOf(pageable.getPageSize()));

            //设置报文头
            Header header = new Header();
            header.setVersion(BusinessContainer.BOMP_VERSION);
            header.setTransDate(CommonUtils.getCurrentDate("yyyyMMdd"));
            header.setTransTime(CommonUtils.getCurrentDate("HHmmss"));
            header.setTxnNum(MompTxnNumEnum.MEMBER_INFO.getType());
            header.setBizType(BusinessContainer.IGAS_DEFAULT_BIZ_TYPE);
            header.setInstId(user.getInstId());
            header.setSrcSysId(BusinessContainer.MOMP_SRC_SYS_ID);
            header.setChanlId(BusinessContainer.MOMP_SRC_SYS_ID);
            header.setTraceNo(user.getInstId().substring(0, 3) + orgCode + MompTxnNumEnum.MEMBER_INFO.getType() + DateUtils.formatDate(new Date(), DateUtils.FULL_SEQ_FORMAT));
            queryParam.setHeader(header);
            log.info("查询会员列表 请求报文：{}", JSON.toJSONString(queryParam));
            result = queryMemberInfoService.queryMemberInfo(queryParam);
            log.info("查询会员列表 应答报文：{}", JSON.toJSONString(result));
        } catch (Exception e) {
            log.error("查询会员列表时系统异常:[{}]", e);
            throw new RedpException("查询会员列表时系统异常");
        }
        if (!result.isSuccess()) {
            log.error("查询会员列表失败:result=[{}]", JSON.toJSONString(result));
            throw new RedpException("查询会员列表失败");
        }

        Page<MembershipInfoBean> page = new Page<>();
        SortUtil.handlePageSort(pageable, page);
        if (null == result.getResult().getMemberInfoList()) {
            log.info("查询会员列表时没有返回数据:result=[{}]", JSON.toJSONString(result.getResult()));
            page.setRecords(null);
            page.setTotal(0L);
        } else {
            page.setRecords(result.getResult().getMemberInfoList());
            page.setTotal(new Long(result.getResult().getTotalRows()));
        }

        return page;
    }

    /**
     * 查询会员详情
     *
     * @param queryParam
     * @param pageable
     * @return
     */
    public IPage<MembershipDetailInfoBean> getMemberDetailList(QueryMemberDetailInfoRequest queryParam, QueryRequest pageable) throws RedpException {
        Result<QueryMemberDetailInfoResponse> result = null;
        try {
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            String orgCode = getOrgCode(user.getOrgCode());
            //设置入参
            queryParam.setQueryId(user.getId());
            queryParam.setQueryOrgId(user.getOrgCode());
            queryParam.setPageIndex(String.valueOf(pageable.getPageNum()));
            queryParam.setPageSize(String.valueOf(pageable.getPageSize()));

            //设置报文头
            Header header = new Header();
            header.setVersion(BusinessContainer.BOMP_VERSION);
            header.setTransDate(CommonUtils.getCurrentDate("yyyyMMdd"));
            header.setTransTime(CommonUtils.getCurrentDate("HHmmss"));
            header.setTxnNum(MompTxnNumEnum.MEMBER_DETAIL.getType());
            header.setBizType(BusinessContainer.IGAS_DEFAULT_BIZ_TYPE);
            header.setInstId(user.getInstId());
            header.setSrcSysId(BusinessContainer.MOMP_SRC_SYS_ID);
            header.setChanlId(BusinessContainer.MOMP_SRC_SYS_ID);
            header.setTraceNo(user.getInstId().substring(0, 3) + orgCode + MompTxnNumEnum.MEMBER_DETAIL.getType() + DateUtils.formatDate(new Date(), DateUtils.FULL_SEQ_FORMAT));
            queryParam.setHeader(header);
            log.info("查询会员列表 请求报文：{}", JSON.toJSONString(queryParam));
            result = queryMemberInfoService.queryMemberDetailInfo(queryParam);
            log.info("查询会员列表 应答报文：{}", JSON.toJSONString(result));
        } catch (Exception e) {
            log.error("查询会员列表时系统异常:[{}]", e);
            throw new RedpException("查询会员列表时系统异常");

        }
        if (!result.isSuccess()) {
            log.error("查询会员列表失败:result=[{}]", JSON.toJSONString(result));
            throw new RedpException("查询会员列表失败");
        }
        Page<MembershipDetailInfoBean> page = new Page<>();
        SortUtil.handlePageSort(pageable, page);
        if (null == result.getResult().getMemberDetailInfoList()) {
            log.info("查询会员列表时没有返回数据:result=[{}]", JSON.toJSONString(result.getResult()));
            page.setRecords(null);
            page.setTotal(0L);
        } else {
            page.setRecords(result.getResult().getMemberDetailInfoList());
            page.setTotal(new Long(result.getResult().getTotalRows()));
        }

        return page;
    }

}
